﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace CodeCamp12
{
    /// <summary>
    /// Summary description for GetSourseForSession
    /// </summary>
    public class GetSourseForSession : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var sessionId = HttpContext.Current.Request.QueryString["id"];
            try
            {
                string[] sessionDirs =
                    Directory.GetDirectories(
                        HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions",
                        "*" + sessionId, SearchOption.AllDirectories);

                string[] files = Directory.GetFiles(sessionDirs[0], "*.rar");
                if(files.Length != 0)
                {
                    foreach (var file in files)
                    {
                        var fileInfo = new System.IO.FileInfo(file);
                        context.Response.Clear();
                        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                        context.Response.ContentType = "application/x-rar-compressed";
                        context.Response.TransmitFile(fileInfo.FullName);
                        context.Response.Flush();
                    }
                }
                else
                {
                        context.Response.Write("There is no source code attached for that session.");
                }


            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}